package org.example.admin.controller.liu;

import cn.hutool.crypto.SecureUtil;
import io.jsonwebtoken.Claims;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.example.admin.entity.EleUser;
import org.example.admin.service.UserService;
import org.example.util.AliyunOSSUtil;
import org.example.util.JwtUtils;
import org.example.util.R;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;

@RestController
@RequestMapping("/ele")
public class UserController {
    @PostMapping("/user/AliyunOss")
    public String AliyunOss(MultipartFile  file){
        return AliyunOSSUtil.upLoad(file);
    }

    @Resource
    private UserService userService;

    @PostMapping("/user/login")
    public R login(@RequestBody EleUser sysUser) {
        EleUser sysUser1 = userService.selectUserByName(sysUser.getUsername());
        if (sysUser1 == null) {
            return R.fail("用户不存在");
        }

        if (!sysUser1.getPassword().equals(SecureUtil.md5(sysUser.getPassword()))) {
            return R.fail("密码错误");
        }
        HashMap<String, Object> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put("userId", sysUser1.getUserid());
        String jwt = JwtUtils.createJwt(objectObjectHashMap);
        return R.ok(jwt);
    }

    @GetMapping("/user/info")
    public R Info(@RequestParam(value = "token") String token) {
        Claims claims = JwtUtils.parseJWT(token);
        Object userId = claims.get("userId");
        EleUser sysUser = userService.selectUserById(Long.parseLong(userId.toString()));
        return R.ok(sysUser);
    }
    @PostMapping("/user/register")
    public R Register(@RequestBody EleUser eleUser) {
        EleUser eleUser1 = userService.selectUserByName(eleUser.getUsername());
        if (eleUser1 != null) {
            return R.fail("用户已存在");
        }
        String s = SecureUtil.md5(eleUser.getPassword());
        eleUser.setPassword(s);

        return R.ok(userService.insertUser(eleUser));
    }


    @GetMapping("/user/selectUserById")
    public R selectUserById(Long userId) {
        return R.ok(userService.selectUserById(userId));
    }


    @GetMapping("/user/selectUserByName")
    public R selectUserByName(String userName) {
        return R.ok(userService.selectUserByName(userName));
    }

    @PostMapping("/user/update")
    public R update(@RequestBody EleUser eleUser) {

        if(eleUser == null) {
            return R.fail("数据错误");
        }
        EleUser user = eleUser;
        user.setPassword(SecureUtil.md5(eleUser.getPassword()));
        int sign =  userService.updateUser(user);
        if (sign > 0) {
            return R.ok("修改成功");
        }
        return R.fail("修改失败");
    }
}
